package com.woniu.cq.mallorder.controller;


import com.woniu.cq.mallorder.common.Result;
import com.woniu.cq.mallorder.domain.Order;
import com.woniu.cq.mallorder.domain.Orderitem;
import com.woniu.cq.mallorder.service.IOrderService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author daniel
 * @since 2020-09-19
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /*@GetMapping("/createOrder")
    public int createOrder(Integer userId) {
        try{
            int order = orderService.createOrder(userId);
            return order;
        }catch (Exception e){
            e.printStackTrace();
            return -1;
        }

    }*/

    /**
     * @description: 某个用户所有订单
     * @param: userId
     * @return: com.woniu.cq.mallorder.common.Result
     */
    @GetMapping("/myOrder")
    public Result myOrder(Integer userId) {
        List<Order> myOrder = orderService.myOrder(userId);
        return Result.builder().code(200).msg("查询成功").data(myOrder).build();
    }

    /**
     * @description: 修改订单状态
     * @param: orderId
     * @return: com.woniu.cq.mallorder.common.Result
     */
    @PostMapping("/changeStatus")
    public Result changeStatus(Integer orderId) {
        orderService.changeStatus(orderId);
        return Result.builder().code(200).msg("修改成功").build();
    }

    /**
     * @description: 新增订单
     * @param: userId
     * @return: com.woniu.cq.mallorder.common.Result
     */
    @GetMapping("/createOrder")
    public int createOrder(Integer userId) {
        try {
            Message<Integer> message = MessageBuilder.withPayload(userId)
                    .setHeader("KEYS", UUID.randomUUID().toString())
                    .setHeader("statusId", UUID.randomUUID().toString())
                    .build();
            rocketMQTemplate.sendMessageInTransaction("topic", message, userId);
            String orderId = stringRedisTemplate.opsForValue().get("orderId");
            int order = Integer.parseInt(orderId);
            return order;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }

    }

}

